import { message } from 'antd';
import api from '../../services';
const { addArticle, updateUploadFile, queryArticleByArticleId, updateArticle, queryTag, addMdArticle } = api;

export default {
  namespace: 'article',

  state: {
    article: {},
    tagList: [],
  },

  subscriptions: {
    setupHistory({ dispatch, history }) {  // eslint-disable-line
      return history.listen(({ pathname, state }) => {
        if (pathname === '/article') {
          if (state && state.editArticleId) {
            dispatch({ type: "queryArticle", payload: { articleId: state.editArticleId, userId: 0 } });
          }
          dispatch({ type: "getTag" });
          return;
        }
        if (pathname !== '/article') {
          dispatch({ type: "updateState", payload: { article: {} } });
        }
      })
    },
  },
  effects: {
    *queryArticle({ payload }, { put, call, select }) {
      const result = yield call(queryArticleByArticleId, payload);
      if (result.code === 0) {
        yield put({ type: "updateState", payload: { article: result.data } });
      }
      else {
        message.error(result.message, 1);
      }
    },
    *getTag({ }, { put, call }) {
      const payload = { categoryId: 0 };
      const result = yield call(queryTag, payload);
      if (result.code === 0) {
        yield put({ type: "updateState", payload: { tagList: result.data } });
      }
      else {
        message.error(result.message, 2);
      }
    },
    *addArticle({ payload }, { put, call, select }) {
      const result = yield call(payload.type === 'md' ? addMdArticle : addArticle, payload);
      if (result.code === 0) {
        if (payload.status === 0) {
          message.success("保存成功");
        } else {
          message.success("发布成功");
        }
      }
      else {
        message.error(result.message, 2);
      }
    },
    *updateUploadFile({ payload, callback }, { put, call, select }) {
      const result = yield call(updateUploadFile, payload);
      callback(result)
    },
    *updateArticle({ payload }, { put, call, select }) {
      const result = yield call(updateArticle, payload);
      if (result.code === 0) {
        if (payload.status === 0) {
          message.success("保存成功");
        } else {
          message.success("发布成功");
        }
        yield put({ type: "updateState", payload: { article: {} } });
      }
    }
  },
  reducers: {
    updateState(state, action) {
      return { ...state, ...action.payload };
    }
  }
};